import React, {useRef, useState} from "react";
import {Button, Col, Form, message, Modal, Row} from "antd";
import {request} from "../../utils/Http";
import {deviceType, page, waitTime} from "../../utils/Const";
import {PlusOutlined} from "@ant-design/icons";
import {ModalForm, ProFormSelect, ProFormText, ProTable} from "@ant-design/pro-components";

const Device = () => {
    const ref = useRef();
    const modelRef = useRef();
    const [modalVisit, setModalVisit] = useState(false);
    const [form] = Form.useForm();  //创建表单实例
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [deviceCode, setDeviceCode] = useState(null);
    const [deviceDataColumns, setDeviceDataColumns] = useState([]);
    const handleOk = () => {
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const columns = [
        {
            title: '设备编号',
            dataIndex: 'deviceCode',
            valueType: 'string',
            editable: true,
        },
        {
            title: '设备类型',
            dataIndex: 'deviceType',
            valueType: 'select',
            editable: false,
            fieldProps: {
                options: deviceType,
            },
        },
        {
            title: '设备名称',
            dataIndex: 'deviceName',
            valueType: 'string',
            editable: false,
        },
        {
            title: '发布topic',
            dataIndex: 'topic',
            valueType: 'string',
            hideInSearch: true,
            renderText: (_, record) => "iot/bs/" + record.deviceCode,
        },
        {
            title: 'Qos',
            dataIndex: 'Qos',
            valueType: 'string',
            hideInSearch: true,
            renderText: (_, record) => "Qos:0",
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            editable: false,
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <Button
                    type="link"
                    onClick={() => {
                        setModalVisit(true)
                        form.setFieldsValue(record)
                    }}
                >
                    编辑
                </Button>,
                <Button type="link" onClick={() => {
                    modelRef.current?.reload();
                    setIsModalOpen(true)
                    setDeviceCode(record.deviceCode)
                    let columns = deviceType.find(obj => obj.value === record.deviceType).columns
                    setDeviceDataColumns([
                        ...columns,
                        ...[{
                            title: '数据编号',
                            dataIndex: 'id',
                            valueType: 'string',
                            hideInSearch: true,
                            hideInTable: true,

                        }, {
                            title: '上报时间',
                            dataIndex: 'reportTime',
                            valueType: 'dateTime',
                            hideInSearch: true,
                            editable: false,
                        },]
                    ])

                }}>
                    数据上报记录
                </Button>,
            ],
        },

    ];

    return (
        <>
            <ProTable
                columns={columns}
                rowKey='deviceCode'
                actionRef={ref}
                search={{
                    labelWidth: 80,
                    // 不同的屏幕尺寸的不同适配
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 4,
                    }
                }}
                request={async (params) => {
                    page.pageSize = params.pageSize;
                    page.pageCurr = params.current;
                    delete params.current
                    params = {...page, ...params}
                    // 获取数据,注意同步异步的问题
                    const data = await request.post({
                        url: "device/page",
                        params: params,
                    }).then(res => {
                        return res.data
                    }).catch(err => {
                        // 这里是错误回调
                        console.log(err)
                    })
                    return {
                        total: data.total,
                        success: true,
                        data: data.records,
                    };
                }}
                dateFormatter="string"
                headerTitle="设备列表"
                toolBarRender={() => [
                    <Button
                        key="button"
                        icon={<PlusOutlined/>}
                        onClick={() => {
                            setModalVisit(true);
                        }}
                        type="primary"
                    >
                        新建
                    </Button>
                    ,
                ]}

            />

            <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <ProTable
                    columns={deviceDataColumns}
                    rowKey='id'
                    actionRef={modelRef}
                    search={false}
                    request={async (params) => {
                        page.pageSize = params.pageSize;
                        page.pageCurr = params.current;
                        delete params.current
                        params = {...page, ...params}
                        // 获取数据,注意同步异步的问题
                        const data = await request.post({
                            url: "device/data-page-code/" + deviceCode,
                            params: params,
                        }).then(res => {
                            return res.data
                        }).catch(err => {
                            // 这里是错误回调
                            console.log(err)
                        })
                        return {
                            total: data.total,
                            success: true,
                            data: data.records,
                        };
                    }}
                    dateFormatter="string"
                    headerTitle="数据上报记录"
                />
            </Modal>

            {/*表单*/}
            <ModalForm
                title="新增设备"
                open={modalVisit}
                onOpenChange={setModalVisit}
                submitTimeout={1000}
                autoFocusFirstInput
                form={form}
                modalProps={{
                    onCancel: () => form.resetFields(),
                    onOk: () => form.resetFields(),
                }}
                onFinish={
                    async (values) => {
                        await waitTime(1000);
                        // 获取数据,注意同步异步的问题
                        request.post({
                            url: "device/add-or-edit",
                            params: values,
                        }).then(res => {
                            message.success("创建成功");
                            ref.current?.reload();
                        }).catch(err => {
                            // 这里是错误回调
                            console.log(err)
                        })
                        return true;
                    }
                }>
                <Row gutter={{
                    xs: 8, sm: 16, md: 24, lg: 32,
                }} justify="space-between">
                    <ProFormText
                        name="deviceCode"
                        hidden
                    />
                    <Col span={12}>
                        <ProFormText name="deviceName" label="设备名称"
                                     rules={[{required: true, message: '设备名称必填!'}]}/>
                    </Col>
                    <Col span={12}>
                        <ProFormSelect name="deviceType" label="设备类型"
                                       request={async () => deviceType}
                                       rules={[{required: true, message: '设备类型必填!'}]}/>
                    </Col>
                </Row>
            </ModalForm>
        </>
    )
}

export default Device;